<template>
  <ContentWrap>
    <back :backOption="backOption" />
    <div>
      <el-card shadow="never">
        <template #header>
          <span>{{ infoOptions.data.dataSourceName || infoOptions.data.name || '--' }}</span>
        </template>
        <el-descriptions :column="infoOptions.column">
          <div v-for="(item, index) in infoOptions.columns" :key="index">
            <el-descriptions-item :label="item.label">
              <span v-if="item.key == 'ip'">
                <div
                  v-if="item.key == 'ip'"
                  class="inline-flex"
                  style="justify-content: space-between; width: 160px; align-items: center"
                >
                  <span v-if="isShowIp" class="mr-10px">
                    {{ infoOptions.data.ip }}:{{ infoOptions.data.port }}
                  </span>
                  <span v-else class="mr-10px">**********</span>
                  <el-Icon v-if="isShowIp"><Hide @click="isShowIp = false" /></el-Icon>
                  <el-Icon v-else>
                    <View @click="isShowIp = true" />
                  </el-Icon>
                </div>
              </span>
              <span v-else-if="item.key == 'source'">
                {{
                  sourceMap.has(infoOptions.data.source)
                    ? sourceMap.get(infoOptions.data.source)
                    : '--'
                }}
              </span>
              <span v-else> {{ infoOptions.data[item.key] || '--' }}</span>
            </el-descriptions-item>
          </div>
        </el-descriptions>
        <el-descriptions :column="filedOptions.column" class="mt-16px">
          <div v-for="(item, index) in filedOptions.columns" :key="index">
            <el-descriptions-item
              label-class-name="font-size-16px"
              class-name="font-size-16px"
              :label="item.label"
              >{{ filedOptions.data[item.key] || '0' }}</el-descriptions-item
            >
          </div>
        </el-descriptions>
      </el-card>
      <el-card class="mt-16px" shadow="never">
        <el-form label-width="100px" ref="formRef" :model="searchValue">
          <el-row>
            <el-col :span="6">
              <el-form-item label="文件名称" prop="fileName">
                <ns-input v-model="searchValue.fileName" clearable placeholder="请输入文件名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="文件类型" prop="fileType">
                <ns-input v-model="searchValue.fileType" clearable placeholder="请输入文件类型" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="分级" prop="level">
                <el-select v-model="searchValue.level" clearable placeholder="请选择分级">
                  <el-option
                    v-for="(level, levelIndex) in levelList"
                    :key="levelIndex"
                    :label="level.levelName"
                    :value="level.levelCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="重要程度" prop="importance">
                <el-select v-model="searchValue.importance" clearable placeholder="请选择重要程度">
                  <el-option label="重要数据" value="重要数据" key="1" />
                  <el-option label="公开数据" value="公开数据" key="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="自动分级状态" prop="autoClassStatus">
                <el-select
                  v-model="searchValue.autoClassStatus"
                  clearable
                  placeholder="请选择分级状态"
                >
                  <el-option
                    v-for="(item, index) in autoClassStatusMap"
                    :key="index"
                    :label="item[1]"
                    :value="item[0]"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="提交状态" prop="submitStatus">
                <el-select
                  v-model="searchValue.submitStatus"
                  clearable
                  placeholder="请选择提交状态"
                >
                  <el-option label="已提交" value="1" />
                  <el-option label="未提交" value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否已分级">
                <el-select v-model="searchValue.isLevel" clearable placeholder="请选择是否已分级">
                  <el-option label="已分级" :value="true" />
                  <el-option label="未分级" :value="false" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="text-right">
              <el-button
                @click="search"
                type="primary"
                v-hasPermi="['assetList:fileServerDetail:search']"
                >搜索</el-button
              >
              <el-button
                @click="searchReset"
                plain
                v-hasPermi="['assetList:fileServerDetail:reset']"
                >重置</el-button
              >
            </el-col>
          </el-row>
        </el-form>
        <el-divider />
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="handleUpdateList"
          v-hasPermi="['assetList:fileServerDetail:batchEdit']"
          >批量修改</el-button
        >
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="handleSubmit"
          v-hasPermi="['assetList:fileServerDetail:batchSubmit']"
          >批量提交</el-button
        >
        <el-button plain @click="handleExport" v-hasPermi="['assetList:fileServerDetail:export']"
          >导出</el-button
        >
        <!-- <el-button plain @click="handleImport" v-hasPermi="['assetList:fileServerDetail:import']"
          >导入</el-button
        > -->
        <AsyncTable
          class="mt-12px"
          ref="tableRef"
          @selection-change="changeTable"
          :fetchData="fetchData"
          v-bind="tableOptions"
        />
      </el-card>
      <!-- 批量修改弹窗 -->
      <UpdateListLevel ref="updateListRef" @success="search" />
    </div>
    <ImportForm ref="importFormRef" @success="search" />
  </ContentWrap>
</template>

<script setup lang="tsx">
import ImportForm from '@/views/asset/assetList/components/ImportForm.vue'
import { sourceMap } from '@/utils/dict'
import { useRoute } from 'vue-router'
import { DescriptionsProps } from '@/types/descriptions'
import { autoClassStatusMap } from '@/utils/dict'
import { Hide, View } from '@element-plus/icons-vue'
import {
  getDataBaseList,
  getDataSourceDetail,
  assetMessageExportExcelFile,
  assetPageByLevelCount,
  assetMessageRemoteFromDatasource,
  assetMessageRemoteManyFromDatasource
} from '@/api/assetList/index'
import { levelPage } from '@/api/strategyManage/level/index'
import UpdateListLevel from '@/views/asset/assetList/databaseList/detail/components/updateListLevel.vue'
import dayjs from 'dayjs'
import { checkPermi } from '@/utils/permission'
import { renderFinger, renderClassification, renderLevel } from '@/utils/commonRender'
import download from '@/utils/download'
const message = useMessage() // 消息弹窗
const { proxy } = getCurrentInstance() as any
const route = useRoute()
const assetId = ref<string>(route.query.id as string)
const isShowIp = ref(false)
const backOption = ref({
  title: '返回'
})
const tableRef = ref()
const formRef = ref()

const ids = ref<string[]>([])

const infoOptions: DescriptionsProps = reactive({
  column: 5,
  columns: [
    { label: '资产IP:端口', key: 'ip', isShow: true },
    { label: '资产类型', key: 'assetType', isShow: false },
    { label: '数据来源', key: 'source', isShow: false },
    { label: '归属系统', key: 'sysName', isShow: true },
    { label: '归属机构', key: 'deptName', isShow: false },
    { label: '数据标准', key: 'templateName', isShow: true },
    // { label: '分类分级方式', key: 'classificationWay', isShow: true },
    { label: '启动时间', key: 'startTime', isShow: true },
    { label: '完成时间', key: 'completeTime', isShow: true },
    { label: '执行人', key: 'fake', isShow: true }
  ],
  data: {}
})

const filedOptions: DescriptionsProps = reactive({
  column: 5,
  columns: [
    { label: '总数：', key: 'totalCount' },
    { label: '已分级数：', key: 'level' },
    { label: '未分级数：', key: 'unLevel' }
  ],
  data: {}
})

const tableOptions = reactive({
  columns: [
    {
      type: 'selection'
    },
    { label: '文件名称', prop: 'fileName' },
    { label: '文件类型', prop: 'fileType' },
    { label: '文件大小', prop: 'fileSize' },
    { label: '文件路径', prop: 'absolutePath' },
    { label: '文件指纹', width: '150px', render: renderFinger },
    {
      label: '分类',
      render: renderClassification
    },
    {
      label: '分级',
      render: renderLevel
    },
    {
      label: '提交状态',
      render: ({ row }) => {
        return <span>{row.submitStatus == '1' ? '已提交' : '未提交'}</span>
      }
    },
    {
      label: '操作',
      width: '200px',
      render: ({ row }) => {
        return (
          <>
            {checkPermi(['assetList:fileServerDetail:submit']) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  submitEnsure(row)
                }}
              >
                提交确认
              </el-button>
            )}
            {checkPermi(['assetList:fileServerDetail:edit']) && (
              <el-button link type="primary" onClick={() => grade(row)}>
                编辑
              </el-button>
            )}
          </>
        )
      }
    }
  ],
  data: []
})

const searchValue = ref({
  fileName: '',
  fileType: '',
  isLevel: '',
  importance: '', //重要程度
  classification: '', //分类
  level: '', //分级
  submitStatus: '',
  autoClassStatus: ''
})
const handleSubmit = () => {
  proxy?.$modal
    .confirm(`确定要将所选资产提交至待确认吗？`)
    .then(() => {
      assetMessageRemoteManyFromDatasource(ids.value).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('提交成功')
      })
    })
    .catch(() => {})
}

// 搜索重置
const searchReset = () => {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
  getCount()
}
// 搜索
const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
  getCount()
}
const pageParams = ref({
  page: 1,
  pageSize: 10
})
// 表格数据获取
const fetchData = async ({ page, pageSize }) => {
  pageParams.value = {
    page,
    pageSize
  }
  const { data, count } = await getDataBaseList({
    page,
    pageSize,
    ...searchValue.value,
    parentId: assetId.value
  })
  return { data, count }
}

const updateTableData = () => {
  tableRef.value.fetchData()
}

const submitEnsure = (row) => {
  if (row.submitStatus == '1') {
    ElMessage.error('该资产已提交，请勿重复提交')
    return
  }
  proxy?.$modal
    .confirm(`确定要将该资产提交至待确认吗？`)
    .then(() => {
      assetMessageRemoteFromDatasource(row.id).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('提交成功')
      })
    })
    .catch(() => {})
}

const changeTable = (val) => {
  ids.value = []
  val.map((item) => {
    ids.value.push(item.id)
  })
}

// 批量修改
const updateListRef = ref()
const handleUpdateList = () => {
  updateListRef.value.open(ids.value)
}
// 分级分类（行）
const grade = (row) => {
  proxy?.$Drawer({
    params: {
      ...row,
      type: row.handClassificationName ? `人工` : row.classificationName ? `自动` : '--',
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `分级分类`,
    size: '40%',
    component: import('@/views/asset/assetList/databaseList/detail/components/grade.vue')
  })
}

const exportLoading = ref(true)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await assetMessageExportExcelFile({
      ...pageParams.value,
      ...searchValue.value,
      parentId: assetId.value,
      ids: ids.value
    })
    download.excel(data, '分级结果.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

const getData = async () => {
  const res = await getDataSourceDetail({ id: assetId.value })
  console.log('res', res)
  infoOptions.data = res.data
}
const getCount = async () => {
  const data = await assetPageByLevelCount({ parentId: assetId.value, ...searchValue.value })
  console.log('data', data)
  filedOptions.data = data
}

const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  console.log('data', data)
  levelList.value = data
}

onMounted(async () => {
  getData()
  getCount()
  getLevelList()
})
</script>
